<template>
    <div class="position-map" :style="{ width: mapWidth, height: mapHeight }">
        <div class="map-search">
            <div>
                <el-select
                    v-model="searchKey"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词"
                    :remote-method="handleSearch"
                    @change="handleSelect"
                    :popper-append-to-body="false"
                    class="search"
                >
                    <el-option
                        v-for="item in result"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    >
                        <span style="float: left">{{ item.name }}</span>
                        <span
                            style="float: right; color: #8492a6; font-size: 13px;white-space: pre-wrap;"
                        >
                            {{ item.address }}
                        </span>
                    </el-option>
                </el-select>
                <i @click="handleSearch" class="search-icon el-icon-search" />
            </div>
        </div>
        <AMap @init="plugin" class="map" />
    </div>
</template>
<script>
import AMap from '@/components/AMap'
export default {
    name: 'position-map',
    props: {
        mapWidth: {
            type: String,
            default: '100%'
        },
        mapHeight: {
            type: String,
            default: '100%'
        },
        mapConfig: {
            type: String,
            default: () => {}
        },
        position: {
            type: Object,
            default: () => {}
        },
        code: {
            type: String,
            default: ''
        },
        lng: {
            type: Number,
            default: 0
        },
        lat: {
            type: Number,
            default: 0
        }
    },
    components: {
        AMap
    },
    data() {
        return {
            MapInfo: {},
            marker: null,
            searchKey: '',
            AMap: null,
            map: null,
            result: []
        }
    },
    methods: {
        plugin({ map, AMap, PositionPicker }) {
            this.map = map
            this.AMap = AMap
            console.log('this.position', this.position)
            // if (this.position) {
            //     map.setCenter(this.position)
            // }
            this.map.on('click', data => {
                // console.log(data)
                const lng = data.lnglat.getLng()
                const lat = data.lnglat.getLat()
                const lnglatXY = [lng, lat] // 地图上所标点的坐标
                // console.log('lnglatXY', lnglatXY)

                map.clearMap()
                this.marker = new AMap.Marker({
                    position: [lng, lat] //位置
                })
                map.add(this.marker) //添加到地图
                // map.setFitView(this.marker)
                // 获取点击时的详细地址
                AMap.service('AMap.Geocoder', () => {
                    const geocoder = new AMap.Geocoder({})
                    geocoder.getAddress(lnglatXY, (status, result) => {
                        console.log(result)

                        if (status === 'complete' && result.info === 'OK') {
                            // 获得了有效的地址信息:
                            // 拼接信息
                            const addressComponent =
                                result.regeocode.addressComponent
                            const address =
                                addressComponent.province +
                                addressComponent.city +
                                addressComponent.district
                            // console.log(address)
                            const position = {
                                position: {
                                    lng,
                                    lat
                                },
                                address, // 地址
                                addressDetail: result.regeocode.formattedAddress.replace(
                                    address,
                                    ''
                                ),
                                adcode: addressComponent.adcode,
                                addressComponent
                            }
                            console.log('position', position)
                            this.$emit('drag', position)
                            // 创建纯文本标记
                            const text = new AMap.Text({
                                text: result.regeocode.formattedAddress,
                                anchor: 'center', // 设置文本标记锚点
                                draggable: true,
                                cursor: 'pointer',
                                offset: new AMap.Pixel(0, -64),
                                style: {
                                    padding: '.75rem 1.25rem',
                                    'margin-bottom': '1rem',
                                    'border-radius': '.25rem',
                                    'background-color': 'white',
                                    width: '15rem',
                                    'word-break': 'inherit',
                                    'border-width': 0,
                                    'box-shadow':
                                        '0 2px 6px 0 rgba(114, 124, 245, .5)',
                                    'font-size': '12px',
                                    display: '-webkit-box',
                                    'white-space': 'inherit',
                                    '-webkit-line-clamp': 2,
                                    ' -webkit-box-orient': 'vertical',
                                    color: '#666666'
                                },
                                position: [lng, lat]
                            })
                            text.setMap(map)
                            // this.routeInfoList.push(ipnew)
                            // this.$emit('drag', this.routeInfoList)
                        }
                    })
                })
                console.log(lnglatXY, lng, lat)
            })

            // const positionPicker = new PositionPicker({
            //     mode: 'dragMap', // 设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
            //     map: map // 依赖地图对象
            // })
            if (!this.lat && !this.lng) {
                map.plugin('AMap.Geolocation', () => {
                    const geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true, // 是否使用高精度定位，默认:true
                        timeout: 10000, // 超过10秒后停止定位，默认：无穷大
                        maximumAge: 0, // 定位结果缓存0毫秒，默认：0
                        convert: true, // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                        showButton: true, // 显示定位按钮，默认：true
                        buttonPosition: 'LB', // 定位按钮停靠位置，默认：'LB'，左下角
                        buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                        showMarker: true, // 定位成功后在定位到的位置显示点标记，默认：true
                        showCircle: true, // 定位成功后用圆圈表示定位精度范围，默认：true
                        panToLocation: true, // 定位成功后将定位到的位置作为地图中心点，默认：true
                        resizeEnable: true
                        // zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    })

                    geolocation.getCurrentPosition()
                    AMap.event.addListener(
                        geolocation,
                        'complete',
                        this.onComplete
                    )
                    AMap.event.addListener(geolocation, 'error', this.onError)
                })
            }
            // // 拖拽完成发送自定义 drag 事件
            // positionPicker.on('success', (positionResult) => {
            //     // 过滤掉初始化地图后的第一次默认拖放
            //     const address = `${positionResult.regeocode.addressComponent.province}${positionResult.regeocode.addressComponent.city}${positionResult.regeocode.addressComponent.district}`
            //     const addressDetail = positionResult.address.slice(address.length)
            //     const position = {
            //         position: positionResult.position,
            //         address: address,
            //         addressDetail: addressDetail,
            //         adcode: positionResult.regeocode.addressComponent.adcode,
            //         addressComponent: {
            //             province: positionResult.regeocode.addressComponent.province,
            //             city: positionResult.regeocode.addressComponent.city,
            //             district: positionResult.regeocode.addressComponent.district
            //         }
            //     }
            //     console.log(position)

            //     this.$emit('drag', position)
            // })
            // // 启动拖放
            // positionPicker.start()
        },
        // 定位成功返回 位置和坐标
        onComplete(data) {
            // data是具体的定位信息
            console.log('地图 初始化 完成   定位成功', data)
            const lng = data.position.lng
            const lat = data.position.lat
            const AMap = this.AMap
            const map = this.map
            map.clearMap()
            this.marker = new AMap.Marker({
                position: [lng, lat] //位置
            })
            map.add(this.marker) //添加到地图
            this.MapInfo = data
            const address =
                data.addressComponent.province +
                data.addressComponent.city +
                data.addressComponent.district
            const position = {
                position: this.MapInfo.position,
                address: address,
                adcode: this.MapInfo.addressComponent.adcode,
                addressDetail: this.MapInfo.formattedAddress.replace(
                    address,
                    ''
                ),
                addressComponent: {
                    province: this.MapInfo.addressComponent.province,
                    city: this.MapInfo.addressComponent.city,
                    district: this.MapInfo.addressComponent.district
                }
            }
            this.$emit('drag', position)
            const text = new AMap.Text({
                text: this.MapInfo.formattedAddress,
                anchor: 'center', // 设置文本标记锚点
                draggable: false,
                cursor: 'pointer',
                offset: new AMap.Pixel(0, -64),
                style: {
                    padding: '.75rem 1.25rem',
                    'margin-bottom': '1rem',
                    'border-radius': '.25rem',
                    'background-color': 'white',
                    width: '15rem',
                    'word-break': 'inherit',
                    'border-width': 0,
                    'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
                    'font-size': '12px',
                    display: '-webkit-box',
                    'white-space': 'inherit',
                    '-webkit-line-clamp': 2,
                    ' -webkit-box-orient': 'vertical',
                    color: '#666666'
                },
                position: [lng, lat]
            })
            text.setMap(map)
            // this.$emit('plugin', this, position)
        },
        // 定位失败
        onError(data) {
            console.log('地图 初始化 完成   定位失败', data)
            // this.$emit('plugin', this)
        },
        handleSearch(queryString) {
            const AMap = this.AMap
            const map = this.map
            AMap.plugin('AMap.Autocomplete', () => {
                // 实例化Autocomplete
                const autoOptions = {
                    //city 限定城市，默认全国
                    city: '全国'
                }
                const autoComplete = new AMap.Autocomplete(autoOptions)
                autoComplete.search(queryString, (status, result) => {
                    // console.log(result)
                    if (status === 'complete') {
                        // cb(result.tips)
                        this.result = result.tips
                            .filter(v => v.id)
                            .map(el => {
                                el.address =
                                    Array.isArray(el.address) &&
                                    el.address.length === 0
                                        ? ''
                                        : el.address
                                return el
                            })
                    }
                    // 搜索成功时，result即是对应的匹配数据
                })
            })
        },
        handleSelect(id) {
            console.log(id)
            const item = this.result.find(el => el.id === id)
            const AMap = this.AMap
            const map = this.map
            AMap.service('AMap.PlaceSearch', () => {
                const placeSearch = new AMap.PlaceSearch({
                    // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
                    city: item.adcode,
                    map: map, // 展现结果的地图实例
                    autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
                })

                placeSearch.search(item.name, function(status, result) {
                    // 查询成功时，result即对应匹配的POI信息
                    console.log(result)
                    var pois = result.poiList.pois
                    for (var i = 0; i < pois.length; i++) {
                        const poi = pois[i]
                        const marker = []
                        marker[i] = new AMap.Marker({
                            position: poi.location, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                            title: poi.name
                        })
                        // 将创建的点标记添加到已有的地图实例：
                        map.add(marker[i])
                    }
                    map.setFitView({
                        position: [item.location.lng, item.location.lat]
                    })
                })
                AMap.event.addListener(placeSearch, 'markerClick', m => {
                    const e = m.data
                    const address = e.pname + e.cityname + e.adname
                    const position = {
                        position: {
                            lng: e.location.lng,
                            lat: e.location.lat
                        },
                        address: address, // 地址
                        addressDetail: e.address,
                        adcode: e.adcode,
                        addressComponent: {
                            adcode: e.adcode,
                            province: e.pname,
                            city: e.cityname,
                            district: e.adname
                        }
                    }
                    this.$emit('drag', position)
                })
            })
        }
    },

    created() {
        // 监听事件
        // console.log('position', this.$props.position)
        // this.lat = this.$props.position.code
    },
    destroyed() {
        // 注销事件
    }
}
</script>

<style lang="scss" scoped>
.position-map {
    width: 100%;
    height: 100%;
    min-height: 300px;
    position: relative;
}

.map-search {
    // height: calc(100% - 30px);
}
.map-search > div {
    // height: 100%;
    position: relative;
}
.map-search {
    position: absolute;
    left: 10px;
    top: 10px;
    z-index: 1;
    ::v-deep .search .el-input__inner {
        width: 320px;
        height: 32px;
        background: rgba(255, 255, 255, 1);
        box-shadow: 0px 0px 14px 0px rgba(0, 0, 0, 0.1);
        border-radius: 16px;
    }
    .search {
        ::v-deep .el-select-dropdown__item {
            height: auto;
        }
        ::v-deep .el-scrollbar__wrap {
            max-width: 600px;
        }
    }
}
.search-icon {
    position: absolute;
    right: 11px;
    top: 9px;
    font-size: 14px;
    // color: $--bt--general-primary;
}
#js-result {
    height: calc(100% - 30px);
    ::v-deep .amap_lib_placeSearch {
        height: 100%;
        overflow: auto;
        border-radius: 6px;
    }
}
</style>
